﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using OpenAuth.App;
using Infrastructure;
using OpenAuth.Repository.Domain;
using Microsoft.AspNetCore.Authorization;

namespace OpenAuth.WebApi.Areas.HisApi.Controllers
{

    /// <summary>
    /// 充值接口his端
    /// </summary>
    [Route("HisApi/[controller]/[action]")]
    [ApiController]
    public class PayHisController : ControllerBase
    {
        private readonly BMZXX006App bmzxx006App;
        private readonly BMZXX003App bmzxx003App;
        private readonly CGGYW007App cggyw007App;
        private readonly BMZXX009App bmzxx009App;
        private readonly CMZXX007App cmzxx007App;
        private readonly CMZXX002App cmzxx002App;
        //充值表操作类
        private readonly PayOrderApp payorderApp;
        //退款表操作类
        private readonly RefundOrderApp refundApp;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="_bmzxx006App"></param>
        public PayHisController(BMZXX006App _bmzxx006App, BMZXX003App _bmzxx003App, CGGYW007App _cggyw007App, BMZXX009App _bmzxx009App, CMZXX007App _cmzxx007App, CMZXX002App _cmzxx002App, PayOrderApp _payorderApp,RefundOrderApp _refundApp)
        {
            bmzxx006App = _bmzxx006App;
            bmzxx003App = _bmzxx003App;
            cggyw007App = _cggyw007App;
            bmzxx009App = _bmzxx009App;
            cmzxx007App = _cmzxx007App;
            cmzxx002App = _cmzxx002App;
            payorderApp = _payorderApp;
            refundApp = _refundApp;
        }
        [HttpGet]
        public void test()
        {
            var result = bmzxx009App.CheckRefund(1133633, "TMZYJ_1133633_3312026", 2, -12.10.ToDecimal());
        }

        /// <summary>
        /// 门诊预交金预充值（预约）
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public string QueryHisOrder(string patid, string name)
        {

            var result = bmzxx006App.QueryHisPayNo(patid, name);
            if (result.Count() > 0 && result.First().hisddh != null)
            {
                var temp = result.Select(d => new { hisddh = d.hisddh, sjh = d.jylsh }).First();
                return new { success = "true", requestId = Guid.NewGuid().ToString(), hisddh = temp.hisddh, sjh = temp.sjh.ToString("0") }.ToJson();
            }
            else
            {
                return new { success = "false", requestId = Guid.NewGuid().ToString(), message = "没有查询到数据" }.ToJson();
            }
        }
        /// <summary>
        /// 门诊预交金充值（预约）
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public string YYCardCharge(string patid, string hzxm, string sjh, string hisddh, string ptlsh, int zffs, double zfje, string zflsh, string time)
        {
            BMZXX003 temp = new BMZXX003();
            temp.patid = patid;
            temp.paytype = 2;
            temp.paymoney = zfje;
            temp.paylsh = zflsh; //支付流水号
            temp.paytime = time;
            temp.hisjylsh = sjh;
            temp.ptlsh = ptlsh;
            temp.hisddh = hisddh;
           
            var result = bmzxx003App.PutCardCharge(temp);
            if (result.First().Code == 200)
            {

                return (new { success = "true", requestId = Guid.NewGuid().ToString(), yjxh = result.First().yjxh, dqye = result.First().dgye, hisddh = result.First().hisddh }).ToJson();
            }
            else
            {
                return new { success = "false", requestId = Guid.NewGuid().ToString(), message = result.First().Message }.ToJson();

            }

        }
        /// <summary>
        /// 门诊预交金充值
        /// </summary>
        /// <param name="patid"></param>
        /// <param name="name"></param>
        /// <param name="money"></param>
        /// <returns></returns>
        [HttpGet]
        public string CardCharge(string patid, string name, double money)
        {
            var yResult = bmzxx006App.QueryHisPayNo(patid, name).FirstOrDefault();
            //payorderApp.Update()
            BMZXX003 temp = new BMZXX003();
            temp.patid = patid;
            temp.paytype = 2;
            temp.paymoney = money;
            temp.paylsh = DateTime.Now.ToString("yyyyMMddmm"); //支付流水号
            temp.paytime = "";
            temp.hisjylsh = yResult.jylsh.ToString();
            temp.ptlsh = "33333";
            temp.hisddh = yResult.hisddh;
            var cResult = bmzxx003App.PutCardCharge(temp);
            return cResult.FirstOrDefault().ToJson();
        }
        /// <summary>
        /// 查询外部订单结果(预约)
        /// </summary>
        /// <param name="ptlsh">平台流水号</param>
        /// <param name="sjhlx">类型</param>
        /// <returns></returns>
        [HttpGet]
        public string QueryOutSideOrder(string ptlsh, string sjhlx)
        {
            var result = cggyw007App.QueryOutSideOrder(ptlsh);
            if (result.Count() > 0 && result.First().patid != 0)
            {
                //var wbdjjgs = result.Select(d => new { hisdh = d.hisdh, zt = d.zt });
                var wbdjjgs = from value in result select new { hisdh = value.hisdh, zt = value.zt };
                return (new { success = "true", requestId = Guid.NewGuid().ToString(), wbdjjgs = wbdjjgs }).ToJson();
            }
            else
            {
                return new { success = "false", requestId = Guid.NewGuid().ToString(), message = "没有查询到数据" }.ToJson();
            }
        }
        /// <summary>
        /// 门诊预交金退费(弃用不写本地表的方法)
        /// </summary>
        /// <param name="hzxm">患者姓名</param>
        /// <param name="patid">患者id</param>
        /// <param name="yjxh">预交金序号</param>
        /// <param name="ptlsh">平台流水号</param>
        /// <returns></returns>
        [HttpGet]
        public string Refund(string hzxm, decimal patid, string yjxh, string ptlsh, string hisddh)
        {
            var result = bmzxx009App.Refund(new BMZXX009() { name = hzxm, patid = patid, yjxh = yjxh, ptlsh = ptlsh });
            if (result.First().Code == 200)
            {

                return (new { success = "true", requestId = Guid.NewGuid().ToString(), tfje = result.First().tfje, tsjh = result.First().tsjh, zffs = result.First().zffs, zflsh = result.First().zflsh, thisddh = result.First().tyjxh }).ToJson();
            }
            else
            {
                return new { success = "false", requestId = Guid.NewGuid().ToString(), message = result.First().Message }.ToJson();

            }
        }
        /// <summary>
        /// 查询门诊预交金充值记录(预约)
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public string QuerychargeListWX([FromBody]CMZXX007 model)
        {
            var result1 = cmzxx007App.QueryChargeList(model);
            if (result1.Count() > 0 && result1.First().patid != 0)
            {
                //var mzyjjjls = from value in result select new { yjxh = value.yjxh.ToString("0"), hzxm = value.hzxm, patid = value.patid.ToString("0"), sjh = value.sjh, ptlsh = value.ptlsh, zffs = value.zffs, zfje = value.zfje.ToString("0.00"), zflsh = value.zflsh, zfsj = value.zfsj.Replace(":",""), jlzt = value.jlzt, dqczybz = value.dqczybz };
                var mzyjjjls = result1.Select(value => new { yjxh = value.yjxh.ToString("0"), hzxm = value.hzxm, patid = value.patid.ToString("0"), sjh = value.sjh, ptlsh = value.ptlsh, zffs = value.zffs, zfje = value.zfje.ToString("0.00"), zflsh = value.zflsh, zfsj = value.zfsj.Replace(":", ""), jlzt = value.jlzt });
                return new { success = "true", requestId = Guid.NewGuid().ToString(), mzyjjjls = mzyjjjls }.ToJson();
            }
            else
            {
                return new { success = "false", requestId = Guid.NewGuid().ToString(), message = "查询充值|没有查询到数据" }.ToJson();
            }
        }

        /// <summary>
        /// 查询门诊预交金充值记录
        /// </summary>
        /// <param name="model">传入对象</param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        //如果在前台是JSON绑定，在ASP.NET Core MVC/WebAPi必须要用[FromBody]明确标识
        public string QueryChargeList([FromBody]CMZXX007 model)
        {

            //需要回传 yjjxh:vm.mzyjjjl.yjxh,tkNumber:vm.mzyjjjl.ptlsh
            //获取预交金充值余额
            var modelY = new CMZXX002();
            modelY.hzxm = model.hzxm;
            modelY.patid = model.patid;
            var result_y = cmzxx002App.QueryAccount(modelY).FirstOrDefault();
            
            //获取his中充值记录
            var result_f = cmzxx007App.QueryChargeList(model);
            //获取本地库中退款记录 开始时间采用之前一个月到今天 不采用传过来的参数了
            var result_r = refundApp.GetOrderByPatid(model.patid.ToString(), DateTime.Now.AddDays(-160), DateTime.Now);
            //获取本地库中充值记录 开始时间采用之前一个月到今天 不采用传过来的参数了
            var temp = payorderApp.GetListByPatid(model.patid.ToString(), DateTime.Now.AddDays(-160), DateTime.Now);
            var result = from result_single in result_f
                         join temp_single in temp on result_single.ptlsh equals temp_single.OrderNumber  
                         select new
                         {
                             yjxh = result_single.yjxh,
                             hzxm = result_single.hzxm,
                             jlzt = result_single.jlzt,
                             patid = result_single.patid,
                             ptlsh = result_single.ptlsh,
                             sjh = result_single.sjh,
                             zffs = result_single.zffs,
                             zfje = result_single.zfje,
                             zflsh = result_single.zflsh,
                             zfsj = result_single.zfsj,
                             //本地退款表中的退款状态                          
                         };
            var result1 = from value in result
                          join refundd in result_r on value.ptlsh equals refundd.tkNumber into detail
                          from m in detail.DefaultIfEmpty()
                          select new
                          {
                              yjxh = value.yjxh,
                              hzxm = value.hzxm,
                              jlzt = value.jlzt,
                              patid = value.patid,
                              ptlsh = value.ptlsh,
                              sjh = value.sjh,
                              zffs = value.zffs,
                              zfje = value.zfje,
                              zflsh = value.zflsh,
                              zfsj = value.zfsj,
                              zt=m==null?0:m.tkzt
                          };

            if (result1.Count() > 0 && result1.First().patid != 0)
            {
               
                //var mzyjjjls = from value in result select new { yjxh = value.yjxh.ToString("0"), hzxm = value.hzxm, patid = value.patid.ToString("0"), sjh = value.sjh, ptlsh = value.ptlsh, zffs = value.zffs, zfje = value.zfje.ToString("0.00"), zflsh = value.zflsh, zfsj = value.zfsj.Replace(":",""), jlzt = value.jlzt, dqczybz = value.dqczybz };
                var mzyjjjls = result1.Select(value => new { yjxh = value.yjxh.ToString("0"), hzxm = value.hzxm, patid = value.patid.ToString("0"), sjh = value.sjh, ptlsh = value.ptlsh, zffs = value.zffs, zfje = value.zfje.ToString("0.00"), zflsh = value.zflsh, zfsj = value.zfsj.Replace(":", ""), jlzt = value.jlzt,zt=value.zt ,is180=(DateTime.Now.ToDate()-new DateTime(int.Parse(value.zfsj.Substring(0,4)),int.Parse(value.zfsj.Substring(4,2)),int.Parse(value.zfsj.Substring(6,2)))).TotalDays>= 160?1:0});
                return new { success = "true", requestId = Guid.NewGuid().ToString(), mzyjjjls = mzyjjjls }.ToJson();
            }
            else
            {
                return new { success = "false", requestId = Guid.NewGuid().ToString(), message = "查询充值|没有查询到数据" }.ToJson();
            }
        }
        /// <summary>
        /// 查询门诊患者预交金余额
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public string QueryAccount([FromBody]CMZXX002 model)
        {
            var result = cmzxx002App.QueryAccount(model);
            if (result.Count() > 0 )
            {
                var mzyjjxxs = from value in result select new { yjjlj = value.yjjlj.ToDouble()==0.000?0: value.yjjlj, yjjye = value.yjjye.ToDouble()==0.000?0:value.yjjye };
                return new { success = "true", requestId = Guid.NewGuid().ToString(), mzyjjxxs = mzyjjxxs }.ToJson();
            }
            else
            {
                return new { success = "false", requestId = Guid.NewGuid().ToString(), message = "查询预交金|没有查询到数据" }.ToJson();
            }
        }
    }
}



#region 关于fromform frombody

//[FromHeader]
//请求标头
//[FromQuery] 请求查询字符串参数
//[FromForm]  请求正文中的表单数据
//[FromBody] 请求正文
//[FromRoute] 当前请求中的路由
//[FromServices] 作为操作参数插入的请求服务

//https://www.cnblogs.com/mmzuo-798/p/11634055.html
//https://www.cnblogs.com/KQNLL/p/10322143.html

//发送的请求头 application/x-www-form-urlencoded 这应该是最常见的 POST 提交数据的方式了。浏览器的原生 <form> 表单，如果不设置 enctype 属性，那么最终就会以 application/x-www-form-urlencoded 方式提交数据。
//POST http://www.example.com HTTP/1.1
//   Content-Type: application/x-www-form-urlencoded;charset=utf-8
//   title=test&sub%5B%5D=1&sub%5B%5D=2&sub%5B%5D=3
//讲解请求头https://www.cnblogs.com/mmzuo-798/p/11634055.html
//https://www.cnblogs.com/KQNLL/p/10322143.html

//FromQuery,对应 url 中的 urlencoded string （"?key1=value1&key2=value2"）。


//FromForm,对应 request content 中的 urlencoded string（"key1=value1&key2=value2"）。


//FromBody,对应 request content 中的 JSON string（"{"key1":"value1","key2":"value2"}"）。

#endregion